package com.example.onlineanswer.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.onlineanswer.common.annotation.RequiresLogin;
import com.example.onlineanswer.common.api.CommonResult;
import com.example.onlineanswer.model.entity.Comment;
import com.example.onlineanswer.model.vo.CommentVO;
import com.example.onlineanswer.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

/**
 * 评论控制器
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class CommentController {

    private final CommentService commentService;

    /**
     * 获取竞赛评论列表
     *
     * @param contestId 竞赛ID
     * @param current   当前页码
     * @param size      每页大小
     * @return 评论列表
     */
    @GetMapping("/contests/{contestId}/comments")
    public CommonResult<IPage<CommentVO>> getContestComments(
            @PathVariable Long contestId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        Page<CommentVO> page = new Page<>(current, size);
        IPage<CommentVO> comments = commentService.pageCommentsByContestId(page, contestId);
        return CommonResult.success(comments);
    }

    /**
     * 发表评论
     *
     * @param contestId 竞赛ID
     * @param userId    用户ID
     * @param comment   评论内容
     * @return 评论ID
     */
    @PostMapping("/contests/{contestId}/comments")
    @RequiresLogin
    public CommonResult<Long> addComment(
            @PathVariable Long contestId,
            @RequestParam Long userId,
            @RequestBody Comment comment) {
        comment.setContestId(contestId);
        comment.setUserId(userId);
        Long commentId = commentService.addComment(comment);
        return CommonResult.success(commentId);
    }

    /**
     * 回复评论
     *
     * @param contestId 竞赛ID
     * @param commentId 评论ID
     * @param userId    用户ID
     * @param comment   回复内容
     * @return 回复ID
     */
    @PostMapping("/contests/{contestId}/comments/{commentId}/replies")
    @RequiresLogin
    public CommonResult<Long> replyComment(
            @PathVariable Long contestId,
            @PathVariable Long commentId,
            @RequestParam Long userId,
            @RequestBody Comment comment) {
        comment.setUserId(userId);
        Long replyId = commentService.replyComment(contestId, commentId, comment);
        return CommonResult.success(replyId);
    }

    /**
     * 点赞评论
     *
     * @param commentId 评论ID
     * @return 是否成功
     */
    @PostMapping("/comments/{commentId}/like")
    @RequiresLogin
    public CommonResult<Boolean> likeComment(@PathVariable Long commentId) {
        boolean success = commentService.likeComment(commentId);
        return CommonResult.success(success);
    }
} 